package cn.wolfcode.shop.web.controller;

import cn.wolfcode.shop.exception.CustomException;
import cn.wolfcode.shop.vo.JsonResultVO;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;


/**
 * 同一异常处理
 */
@ControllerAdvice
public class CommonExceptionHandler {
    /**
     * 捕获自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public JsonResultVO customExceptionHandler(CustomException e){
        e.printStackTrace();
        return JsonResultVO.error(e.getMessage());
    }

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public JsonResultVO bindExceptionHandler(BindException e){
        List<ObjectError> errors = e.getAllErrors();
        StringBuilder sb = new StringBuilder();
        for(ObjectError error : errors){
            sb.append(";").append(error.getDefaultMessage());
        }
        e.printStackTrace();
        return JsonResultVO.error(sb.toString()) ;
    }

    /**
     * 捕获自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public JsonResultVO exceptionHandler(Exception e){
        e.printStackTrace();
        return JsonResultVO.error("系统异常,请稍后再试试");
    }


}
